import fs from 'fs';
import etag from 'etag';
import http from 'http';

import mime from './common/mime.json';

/**
 * 设置响应头部
 *
 * @param request   请求对象
 * @param response  响应对象
 * @param assetPath 资源请求路径
 * @param suffix    资源后缀
 * @param openGZip  开启 GZip 压缩
 */
function setHeaders(request: http.IncomingMessage, response: http.ServerResponse, assetPath: string, suffix: undefined | string, openGZip: boolean): void {
    const { headers } = request;

    const dataSize = fs.statSync(assetPath).size;

    let contentType = headers['content-type'];
    if (!contentType) {
        if (suffix) {
            contentType = (mime as Record<string, string>)[suffix];
        } else {
            contentType = 'text/plain';
        }
    }

    let contentRange = '';
    if (/mpeg$/.test(contentType)) {
        contentRange = `bytes 0-${dataSize - 1}/${dataSize}`;
    }

    let contentEncoding = '';
    if (openGZip) {
        contentEncoding = 'gzip';
    }

    contentType && response.setHeader('Content-Type', contentType);
    contentRange && response.setHeader('Content-Range', contentRange);
    contentEncoding && response.setHeader('Content-Encoding', contentEncoding);

    response.setHeader('Accept-Ranges', 'bytes');
    response.setHeader('Cache-Control', 'public');
    response.setHeader('Content-Length', dataSize);
    response.setHeader('ETag', etag(fs.statSync(assetPath)));
}

export default setHeaders;
